package com.osdp.auth.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osdp.auth.entity.SysOauth2Client;
import com.osdp.auth.mapper.SysOauth2ClientMapper;
import com.osdp.auth.server.ISysOauth2ClientService;
import com.osdp.auth.vo.SysOauth2ClientVo;
import com.osdp.common.util.BeansUtil;
import com.osdp.common.util.ConvertUtil;
import com.osdp.uc.vo.UcPositionVo;
import com.osdp.util.Fields;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysOauth2ClientServiceImpl extends ServiceImpl<SysOauth2ClientMapper, SysOauth2Client> implements ISysOauth2ClientService {

    @Value("${tenant.base.tenantId}")
    private String defaultTanantId;


    @Override
    public IPage<SysOauth2ClientVo> pageList(SysOauth2ClientVo oauth2ClientVo, Page<SysOauth2Client> page) {
        return super.page(page, new QueryWrapper<SysOauth2Client>()
                .eq(StringUtils.isNotBlank(oauth2ClientVo.getScope()),Fields.SysOauth2ClientQ.scope,oauth2ClientVo.getScope())
        ).convert(track -> BeansUtil.copy(track, new SysOauth2ClientVo()));
    }

    @Override
    public boolean updateOauth2Client(SysOauth2ClientVo oauth2ClientVo) {
        SysOauth2Client entity = ConvertUtil.sourceToTarget(oauth2ClientVo,SysOauth2Client.class);
        return super.updateById(entity);
    }

    @Override
    public boolean deleteOauth2Client(List<String> ids) {
        return super.removeByIds(ids);
    }

    @Override
    public boolean saveOauth2Client(String clientId, String secret, String grantTypes, String redirectUri, String tenantId) {
        SysOauth2Client client = new SysOauth2Client();
        client.setClientSecret(secret);
        client.setScope("all");
        client.setAuthorizedGrantTypes(grantTypes);
        client.setWebServerRedirectUri(redirectUri);
        client.setAutoApprove("true");
        client.setTenantId(defaultTanantId);
        if(StringUtils.isNotEmpty(tenantId)){
            client.setTenantId(tenantId);
        }
        return super.save(client);
    }
}
